package com.xuzz.study.io.netty.rpc.consumer;

import com.alibaba.fastjson.JSON;
import com.xuzz.study.io.netty.rpc.base.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @author zhize.xu
 * @version 1.0
 * @ClassName:HelloClientHandler
 * @Description:
 * @date 2018/11/27 16:34
 */
public class HelloClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private String result;
    private RpcRequest request;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 收到服务端数据，唤醒等待线程
     */
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        result = msg.toString();
        notify();
    }

    /**
     * 写出数据，开始等待唤醒
     */
    @Override
    public synchronized Object call() throws InterruptedException {
//        context.writeAndFlush(request);
        String requestJson= JSON.toJSONString(request);
        ByteBuf bytes = Unpooled.copiedBuffer(requestJson.getBytes());
        context.writeAndFlush(bytes);
        wait();
        return result;
    }

    void setPara(RpcRequest request) {
        this.request = request;
    }
}
